var pGrid, pGridData, opt, picking_id, udata,picking_data;
$(function() {
    //ldz 设置表单高度
    $("#form_core").height($(".form_tab").height()-$("#form_option").outerHeight());
    //ldz tab 从表切换事件
    $('#myTabs a').click(function (e) {
	  e.preventDefault()
	  $(this).tab('show')
	});
		
//	$("#layout_main").ligerLayout({
//		bottomHeight : "46%",
//		allowBottomResize : false
//	});//ldz

//	$("form").ligerForm();//ldz

//	$("#d-menu").ligerToolBar({items:[
//	              				    {text:'编辑'},
//	              					{line:true},
//	              					{text:'保存',click:toSave,icon:'save'},
//	              				    {line:true}, 
//	              				    {text:'返回',click:toBack,icon:'back'},
//	              				    {line:true}, 
//	              				    {text:'清空',click:resetArea,icon:'clear'},
//	              					{line:true}
//	              				]});//ldz
//	$("#d-busi—menu").ligerToolBar({items:[
//	                                    {text:'标记为待办任务'  },
//		              				    {line:true},
//		              				    {text:'收货确认'  },
//		              				    {line:true} 
//		              				]});//ldz
	// 明细列表设置
   	pGrid = $("#p-div").ligerGrid({
        columns:[
			{display:'id',name:'product_id',width:'1%',hide:true,
				render: function(rowdata, rowindex, value) {
					if(rowdata.id){
						return rowdata.id;
					}else{
						var currDate = new Date().format("yyyyMMddhhmmss");
						var uuid = Math.uuidFast();
						return currDate+"-"+uuid;
					}
	            }
			},	
			{display:'产品',name:'product_name',width:'10%',
//				editor:{type:'popup',onButtonClick:selectProduct}//ldz
			},
			{display:'内部货号',name:'product_code',width:'10%',textField:'product_code',valueField:'product_code'}, 
            {display:'规格属性',name:'product_att',width:'28%'},
            {display:'数量',name:'product_uom_qty',width:'10%',align:'right',
            	render:function(item){
            		return item.product_uom_qty ? parseFloat(item.product_uom_qty).toFixed(2) : '';
            	}
            },
            {display:'单位',name:'product_uom',width:'10%',
            	render:function(item){
            		return paramRender(item,'uom',item.product_uom);
        		}
            },
            {display:'目的库位',name:'location',width:'10%'},
            {display:'状态',name:'state',width:'10%'},
//            
//            {display:'单位',name:'product_uom',width:60,render:function(item){return paramRender(item,'uom',item.product_uom);}},
//            {display:'品牌',name:'brand',width:80,render:function(item){return paramRender(item,'brand',item.brand);},editor:{type:'select',data:getData('Brand'),valueField:'value',textField:'name'}},
//            {display:'采购数量',name:'tar_product_qty',align:'right',editor:{type:'string'},render:function(item){return item.tar_product_qty ? parseFloat(item.tar_product_qty).toFixed(2) : '';}},
//            {display:'入库数量',name:'product_qty',id:'num',align:'right',editor:{type:'string'},render:function(item){return item.product_qty ? parseFloat(item.product_qty).toFixed(2) : '';}},
//            {display:'采购单价',name:'source_price_unit',align:'right',editor:{type:'string'},render:function(item){return item.source_price_unit ? parseFloat(item.source_price_unit).toFixed(2) : '';}},
//            {display:'入库单价',name:'price_unit',id:'price',align:'right',editor:{type:'string'},render:function(item){return item.price_unit ? parseFloat(item.price_unit).toFixed(2) : '';}},
//            {display:'金额',name:'total',id:'total',align:'right',render:calcTotal},
            //ldz
            {display: '操作', name: 'option', width: '4%',
            	editor: { type: 'button'},
                render: function(rowdata, rowindex, value) {
                	return "<a href='javascript:void(0);' onclick=EditeRow('" + rowindex + "')><span class='glyphicon glyphicon-pencil'></span></a>"+
					"&nbsp;&nbsp;<a href='javascript:void(0);' onclick=deleteRow('" + rowindex + "')><span class='glyphicon glyphicon-trash'></span></a> ";
                }
            }
        ], 
        pageSize:20, 
//        width:'100%',//ldz
        height:'99%', 
        rownumbers:true,
        fixedCellHeight:false, 
        enabledEdit:true, 
        onSelectRow:function(rowdata, rowindex){$("#txtrowindex").val(rowindex);},
        param_partner:'partner_list',
        //ldz
        alternatingRow: true,
        clickToEdit: true,
        isScroll: false,
        usePager:false,
        editorTopDiff:4,
        editorLeftDiff:2
	});
	//明细新增按钮
//	appendAddBtn(function(){
//		pGrid.addEditRow();
//			$(".l-grid2 .l-grid-body-inner").attr("style", "");
//	}, "添加商品明细");//ldz
	//明细删除按钮
//	appendDeleteBtn(deleteRow, "删除商品明细");//ldz
	//解析URL传递的参数
   	
   	// 供应商选择项
	var get_partner_list = new function() {
		return getData('partner_list');
	};
	//业务类型，即分拣类型选择项
	var get_pickType_list = new function() {
		return getData('stock_picktype_list');
	};
	//ldz 为select控件绑定远程数据
	var select_partnerS = bindSelect('partnerS',get_partner_list,[],true);
	var select_pickTypeS = bindSelect('pickTypeS',get_pickType_list,[],false);
	
	var query = getQueryString(window.location.toString());
	opt = query.o;

	if (opt) {
		picking_id = query.picking_id;
		if (opt === 'm') {
			ajaxSubmitGet("/stock/searchStock/" + picking_id, function(data) {
				//绑定数据
				//编辑时值回显
				select_partnerS.val(data['data'].partner_id).trigger("change");
				select_pickTypeS.val(data['data'].picking_type_id).trigger("change");
				bindVal(data);
			});
		}
	} else {
		$("#createDateS").val(new Date().format("yyyy-MM-dd hh:mm:ss"));
		// 附初始值
		// 					ajaxSubmit("/cm/rbac/cmUser.do?method=getUserInfo", null, function(data) {
		// 						$('#deptS').val(data['oname']);
		// 						$('#deptCodeS').val(data['oid']);
		// 						$('#createUserS').val(data['uname']);
		// 						$('#createUserCodeS').val(data['uid']);
		// 						$("#createDateS").val(data['date']);
		// 						$("#WriteDateS").val(data['date']);
		// 					}, null, false);
	}

	udata = getData('user', {
		orgid : $("#deptCodeS").val()
	}, false);

 
	
//	$("#partnerInS").ligerComboBox({
//		autocomplete : true,
//		valueField : 'value',
//		textField : 'name',
//		data : get_partner_list,
//		onSelected : function(v, t) {
//			$("#partnerS").val(v);
//		}
//	});
//	
//	$("#pickTypeInS").ligerComboBox({
//		autocomplete : true,
//		valueField : 'value',
//		textField : 'name',
//		data : get_pickType_list,
//		onSelected : function(v, t) {
//			$("#pickTypeS").val(v);
//		}
//	});

	//ldz 表单验证 start
	/*表单*/
    $.metadata.setType("attr", "validate");
  		//如果一个页面中有多个表单，用  
	$.validator.setDefaults({  
	   debug: true  
	}); 
    var v = $("#formContent form").validate({
        //调试状态，不会提交数据的
        //debug: true,
    	errorPlacement: function (error, element)
        {
        	if(element.prop("tagName")=="SELECT" && element.next().hasClass("select2")){
        		element.parent().removeClass("has-success").addClass("has-error");
        		element.next().attr("data-original-title", error.html());
        		element.next().find(".select2-selection--single").attr("style","border-color:#a94442");
        	}else{
        		element.parent().removeClass("has-success").addClass("has-error");
    	    	//$(element).attr("title", error.html()).ligerTip();//用ligerUI的方法
    	    	element.attr("data-original-title", error.html());
    	        //error.appendTo( element.next() );
        	}
        },
        success: function (lable)
        {
            var element = $("#" + lable.attr("for"));
            if(element.prop("tagName")=="SELECT" && element.next().hasClass("select2")){
            	element.parent().removeClass("has-error").addClass("has-success");
            	element.next().attr("data-original-title", "输入正确");
            	element.next().find(".select2-selection--single").attr("style","border-color: #3c763d");
            }else{
            	element.parent().removeClass("has-error").addClass("has-success");
                element.attr("data-original-title", "输入正确");
                //label.html(" ").addClass("checked");  
    						//label.addClass("valid").text("Ok!")
            }
        },
        submitHandler: function ()
        {
            
        }
    });
    $('[data-toggle="tooltip"]').tooltip();
	//ldz 表单验证 end
	$("#pageloading").hide();
});
function bindVal(data) {
	picking_data = data['data']; 
	//绑定主表数据 
	 
	$('#codeS').val(picking_data.code);
	$('#origin').val(picking_data.origin);
	$('#partnerInS').val(paramRender(null, 'partner_list', picking_data.partner_id));
	$('#partnerS').val(picking_data.partner_id);
	$('#pickTypeInS').val(paramRender(null, 'stock_picktype_list', picking_data.picking_type_id));
	$('#pickTypeS').val(picking_data.picking_type_id);
	$('#predDateS').val(picking_data.min_date); 
	$('#noteS').val(picking_data.note);
	$('#deptS').val(paramRender(null, 'org_list', picking_data.dept_id));
	$('#deptCodeS').val(picking_data.dept_id);
	$('#createUserS').val(paramRender(null, 'user', picking_data.create_uid)); 
	$('#createDateS').val(picking_data.create_date);

	//明细列表数据加载
	pGrid.setOptions({
		data : {
			Rows : picking_data['items']
		}
	}); //设置数据参数
	pGrid.loadData();//加载数据 
}
// 产品明细选择
var curRow, selDialog;
function selectProduct() {
	selDialog = $.ligerDialog.open({
		height : 400,
		width : 650,
		isResize : true,
		url : '../select/product_select.html?o=s',
		title : '选择商品',
		buttons : [
				{
					text : '确定',
					onclick : function(item, dialog) {
						var data = dialog.frame.getSelectedRow();
						select_ondblclick(data);						 
						dialog.close();
					}
				}, {
					text : '取消',
					onclick : function(item, dialog) {
						dialog.close();
					}
				} ]
	});
	return false;
}
//帮助双击自动选中处理方法
function select_ondblclick(data){
    if (!data) {
        $.ligerDialog.warn('请选择商品!');
        return;
    }
    //选择的帮助信息赋值给表单
	pGrid.endEdit();
	pGrid.updateCell('product_id', data.id, pGrid.getSelected());
	pGrid.updateCell('product_code', data.code, pGrid.getSelected());
	pGrid.updateCell('product_name', data.prod_temp_name, pGrid.getSelected());
	pGrid.updateCell('product_att', data.prod_att, pGrid.getSelected());
	pGrid.updateCell('product_uom', data.uom, pGrid.getSelected());
    //初始化变量
 
    //关闭选择窗口
    selDialog.close();
}
// 界面校验
function validate() {
	var valid = true;
	$('*[id$="S"],*[id$="S_txt"]').each(function(index, element) {
		if (!$(this).rules())
			return;
		if (!$(element).valid()) {
			valid = false;
			return;
		}
	});
	if (!valid)
		return false;

	if (pGrid.rows.length === 0) {
		$.ligerDialog.error('请添加入库商品。', '错误');
		return false;
	}

	var r, result;
	var i = 0;
	for (; i < pGrid.rows.length; i++) {
		r = pGrid.rows[i];
		// 					if (!r.code) {
		// 						result = '商品编号不能为空';
		// 						break;
		// 					}
 
		if (!r.product_uom_qty || parseInt(r.product_uom_qty) < 1) {
			result = '入库数量必须录入大于0的整数';
			break;
		}
//		if (!r.source_price_unit || parseInt(r.source_price_unit) === 0.00001) {
//			result = '采购单价必须录入大于0的数值';
//			break;
//		}
//		if (!r.price_unit || parseInt(r.price_unit) === 0.00001) {
//			result = '入库单价必须录入大于0的数值';
//			break;
//		}
//		if (parseInt(r.tar_product_qty) < parseInt(r.product_qty)) {
//			result = "入库数量不能大于采购数量，请修改入库数量";
//			break;
//		}
	}

	if (result) {
		$.ligerDialog.error('入库商品列表第[' + (++i)
				+ ']行存在错误<br/>原因：'.concat(result), '数据错误');
		return false;
	}
	return true;
}

// 保存处理方法 ，新增及修改 。
function toSave() {
	//单据校验
	if (!validate())
		return;
	var url;
	// 设置 主表数据
	var param = new Object();
	
	 
	if(picking_data)
		param =picking_data; 
	// 更新 主表数据	 	
	param.origin = $("#origin").val();
	param.partner_id = $("#partnerS").val();
	param.min_date = $("#predDateS").val();
	param.picking_type_id = $("#pickTypeS").val();
	param.note = $("#noteS").val();
	 
	if (opt === 'm') {
		// 进行修改数据库处理
		//处理主表数据

		param.__status = 'update';

		url = "/stock/updateStock";

	} else {
		// 新增时 数据处理
		param.__status = 'add';
		url = "/stock/saveStock";
		param.state = "draft";
	}
	// 设置 明细数据
	var items = pGrid.rows;
	param.items = items;
	// 提交后台保存数据转换为JSON 格式
	var data = JSON.stringify(param);
	//保存提交后台
	if (url)
		ajaxSubmit(url, data, function(data) {
			if (data['added']) {
				var picking = data['added'];
				picking_id = picking['id'];
			}
			if (parseInt(data['status']) > 0) {
				$.ligerDialog.success('保存成功', '操作完成', reloadPage);
			} else {
				$.ligerDialog.error('保存失败');
			}

		});

}
// 删除明细
function deleteRow(id) {
//	var row = pGrid.getSelectedRow();//ldz
	var row = pGrid.getRow(id);
	if (!row) {
		$.ligerDialog.error('请先选择入库商品记录。', '错误');
		return;
	}
	$.ligerDialog.confirm('您确定要删除该项数据吗？', function(r) {
		if (!r)
			return;
		if (row.__status === 'add') {
			pGrid.deleteRow(row);
			if (pGrid.row && pGrid.row.length === 0)
				pGrid.data = {};
			return;
		}
		var param = new Object();
		param.id = row.id
		var data = JSON.stringify(reqObj('d', 'stock.delete.stock_move', JSON
				.stringify(param)));
		ajaxSubmit("/cm/rbac/cm.do?m=d", data, function(data) {
			if (data) {
				if (parseInt(data['status']) > 0) {
					$.ligerDialog.success('删除成功');
					pGrid.deleteRow(row);
				} else {
					$.ligerDialog.error('删除失败');
				}
			}
		});
	});
}

function calcTotal(item) {
	if (item.product_qty && item.price_unit) {
		return (parseFloat(item.product_qty) * parseFloat(item.price_unit))
				.toFixed(4);
	}
	return '0.0000';
}
// 界面重新载入
function reloadPage() {
	window.location = './stock_picking_detail.html?o=m&picking_id='
			.concat(picking_id);
}
//界面的返回处理，实际是关闭标签处理。
function toBack() {
	//关闭修改界面
	parent.tabManager.removeTabItem("modify_stockp");
	//关闭修改界面1
	parent.tabManager.removeTabItem("modify_stockp1");
	//关闭明细界面
	parent.tabManager.removeTabItem("mx_stockp");
	//关闭新增界面
	parent.tabManager.removeTabItem("new_stockp");
	// new_search_stockS
	parent.tabManager.removeTabItem("new_search_stockS"+$('#codeS').val());
}
//清空表单
function resetArea() {
	toReset('#a_center input:not(.readonly),select,textarea');
}
//新增一行ldz
function addNewRow(data)
{
	pGrid.addRow(data);
}
//弹窗 ldz
var ISEDIT=false;
$(function(){
	$('#pop_add_button').bind('click',function(){
		var data={};
		var pop_add_form = $('#pop_div').find('.modal-body');
		pop_add_form.find("input").each(function(i){
			data[""+$(this).attr('name')+""]=$(this).val();
		});
		pop_add_form.find("select").each(function(i){
			data[""+$(this).attr('name')+""]=$(this).val();
		});
		if(ISEDIT){
			var selected = pGrid.getSelected();
            if (!selected) { alert('请选择行'); return; }
            pGrid.updateRow(selected,data);
		}else{
			addNewRow(data);
		}
	});
})
function addNewRow_pop(){
	$('#addMx_Modal').on('shown.bs.modal', function () {
	});
	ISEDIT=false;
	$('#addMx_Modal').modal('show');
}
function EditeRow(id){
	var data = pGrid.getRow(id);
	$('#addMx_Modal').on('shown.bs.modal', function () {
	  var pop_add_form = $('#pop_div').find('.modal-body');
	  pop_add_form.find("input").each(function(i){
		$(this).val(data[""+$(this).attr('name')+""]);
	  });
	  pop_add_form.find("select").each(function(i){
		$(this).val(data[""+$(this).attr('name')+""]);
	  });
	});
	ISEDIT=true;
	$('#addMx_Modal').modal('show');
}
//产生随机ID ldz
(function() {

  var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  Math.uuid = function (len, radix) 
  {
    var chars = CHARS, uuid = [], i;
    radix = radix || chars.length;

    if (len) {

      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];

    } else {
      var r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random()*16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }

    return uuid.join('');
  };

  Math.uuidFast = function() 
  {
    var chars = CHARS, uuid = new Array(36), rnd=0, r;
    for (var i = 0; i < 36; i++) {
      if (i==8 || i==13 ||  i==18 || i==23) {
        uuid[i] = '-';
      } else if (i==14) {
        uuid[i] = '4';
      } else {
        if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
        r = rnd & 0xf;
        rnd = rnd >> 4;
        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
      }
    }

    return uuid.join('');
  };

  Math.uuidCompact = function() 
  {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) 
	{
      var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
      return v.toString(8);
    });
  };

})();